package Hot100;

import java.util.Stack;

public class 有效的括号 {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (char ch : s.toCharArray()) {
            //碰到左括号，就把相应的右括号入栈
            if (ch == '(' || ch == '[' || ch == '{') stack.push(ch == '(' ? ')' : ch == '[' ? ']' : '}');
            //如果是右括号判断是否和栈顶元素匹配
            else if (stack.isEmpty() || stack.peek() != ch) return false;
            else stack.pop();
        }
        return stack.isEmpty();
    }
}
